import { Injectable, Logger } from '@nestjs/common';
import { CreateAuthDto } from './dto/create-auth.dto';
import { UpdateAuthDto } from './dto/update-auth.dto';
import { UsersService } from '../users/users.service';
import { UserInfo } from '../../common/user-info/user-info.dto';
import { JwtService } from '@nestjs/jwt';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from '../users/entities/user.entity';
import { Repository } from 'typeorm';

const logger = new Logger('auths_service');
@Injectable()
export class AuthsService {
  constructor(
    @InjectRepository(User) private readonly userRepository: Repository<User>,
    private readonly userService: UsersService,
    private readonly jwtService: JwtService,
  ) {}

  async validateUser(userInfo: UserInfo) {
    const user = await this.userService.findOneByUserName(userInfo.username);
    if (user && user.password === userInfo.password) {
      const { password, ...result } = user;
      return result;
    }
    return null;
  }

  async login(userinfo: UserInfo) {
    // const payload = { username: user.username, sub: user.id };
    // return {
    //   access_token: this.jwtService.sign(payload),
    // };
    const { username, password } = userinfo;
    const user = await this.userRepository
      .createQueryBuilder('user')
      .where('user.username = :username', { username })
      .addSelect('user.password')
      .getOne();
    logger.log(JSON.stringify(user));
    if (user && user.password === password) {
      const payload = { username: user.username, sub: user.id };
      return {
        access_token: this.jwtService.sign(payload),
      };
    } else {
      return {
        code: 1,
        message: '该用户不存在，请注册',
      };
    }
  }
}
